﻿@using XRepair.Conventions.Enum
@using xCache = MvcXRepairCustomer.CacheData
@using XRepair.Models

@model MvcXRepair.ViewModel.OrderViewModel

@{
    ViewBag.Title = "xRepair";

    List<State> activeStates = xCache.Cache.GetAllActiveStates();
    var stateList = activeStates.ConvertAll<SelectListItem>(x => new SelectListItem { Value = x.ID.Value.ToString(), Text = x.StateName });
    stateList.Insert(0, new SelectListItem { Value = string.Empty, Text = "- Select state -", Selected = true });

    List<City> activeCities = xCache.Cache.GetAllActiveCities();

    List<SelectListItem> symptomList = ViewBag.SymptomList as List<SelectListItem>;
}
@section head{
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css" />
    <link rel="stylesheet" href="~/Content/jquery.multiselect.css" />
    <link rel="stylesheet" href="~/Content/customerpage.css" />
    <style type="text/css">
        .subTotal
        {
            font-weight: bold;
            font-size: 14px;
        }

            .subTotal td
            {
                padding-bottom: 10px;
                border-bottom: 1px solid #999;
            }

        .pricingDes td
        {
            padding-top: 10px;
        }

        .reset label
        {
            display: inline;
            font-size: 13px;
            font-weight: normal;
            padding-left: 5px;
        }

        #copyBillingAddr
        {
            margin-left: -17px;
        }

        #symptomTab td
        {
            vertical-align: top;
        }

            #symptomTab td:first-child
            {
                padding-right: 5px;
            }

        #symptomDes tr:first-child
        {
            font-weight: bold;
        }

        #symptomDes td
        {
            border: 1px solid #999;
        }

        #frmCollectOrderInfo
        {
            display: none;
        }

        textarea
        {
            resize: none;
        }

        #btnLoginSaveOrder, #btnRegisterSaveOrder
        {
            display: inline;
            background: none;
            border: none;
            font-style: italic;
            text-decoration: underline;
            padding: 0;
            margin: 0;
        }

            #btnLoginSaveOrder:hover, #btnRegisterSaveOrder:hover
            {
                text-decoration: none;
            }
    </style>
}
@using (Html.BeginForm("ProcessOrder", "Home", FormMethod.Post, new { id = "frmCollectOrderInfo" }))
{
    <div id="tabs">
        <ul>
            <li><a href="#tabs-1">Your information</a></li>
            <li><a href="#tabs-2">Symptom information</a></li>
            <li id="btnSummarizeOrder"><a href="#tabs-3">Order summary</a></li>
        </ul>
        <div id="tabs-1">

            <table>
                <tr>
                    <td>Billing Address</td>
                    <td colspan="2">@Html.TextBoxFor(x => x.Address.BillingAddress)</td>
                </tr>
                <tr>
                    <td>Shipping Address</td>
                    <td>@Html.TextBoxFor(x => x.Address.ShippingAddress)</td>
                    <td class="reset">
                        <input type="checkbox" id="copyBillingAddr" /><label for="copyBillingAddr">Same as above</label></td>
                </tr>
                <tr>
                    <td>State</td>
                    <td colspan="2">@Html.DropDownListFor(x => x.Address.State, stateList)
                    </td>
                </tr>
                <tr>
                    <td>City</td>
                    <td colspan="2">@Html.DropDownListFor(x => x.Address.City, new List<SelectListItem> { new SelectListItem { Value = string.Empty, Text = "Waiting for selected state" } })

                    </td>
                    @*                    <td colspan="2">@Html.DropDownListFor(x => x.Address.City, cityList)
                    </td>*@
                </tr>
                <tr>
                    <td>Zip Code</td>
                    <td colspan="2">@Html.TextBoxFor(x => x.Address.ZipCode)</td>
                </tr>
            </table>

            <input type="button" id="btnTab0" value="Continue" />

        </div>
        <div id="tabs-2">
            <p>Check your device's symptom and give us some description:</p>
            <table id="symptomTab">
                @foreach (var symptom in symptomList)
                {
                    bool selected = false;
                    string symptomDes = null;

                    if (Model.SelectedSymptoms != null && Model.SelectedSymptoms.SymptomId != null)
                    {
                        for (int i = 0; i < Model.SelectedSymptoms.SymptomId.Length; i++)
                        {
                            if (Model.SelectedSymptoms.SymptomId[i] == Convert.ToInt32(symptom.Value))
                            {
                                // Symptom is selected in the previous session
                                symptomDes = Model.SelectedSymptoms.SymptomDescription[i];
                                selected = true;
                            }
                        }
                    }
                    <tr>
                        <td>
                            <input type="checkbox" value="@symptom.Value" class="symtomId" id="symptom_@symptom.Value" name="SelectedSymptoms.SymptomId" @if (selected)
                                                                                                                                                         { @Html.Raw("checked='checked'");
                                                                                                                                                         } /></td>
                        <td>
                            <label for="symptom_@symptom.Value">@symptom.Text</label>
                        </td>
                        <td>
                            <textarea cols="30" rows="5" id="des_symptom_@symptom.Value" name="SelectedSymptoms.SymptomDescription" @if (!selected)
                                                                                                                                    { @Html.Raw("class='shadow' disabled='disabled'");
                                                                                                                                    }  >@if (selected)
                                                                                                                                                            {@Html.Raw(symptomDes);
                                                                                                                                                            }</textarea></td>
                    </tr>
                }
            </table>

            <input type="button" id="btnTab1" value="Continue" />
        </div>
        <div id="tabs-3">
            @Html.Partial("OrderSummaryPartial")
            <br />
            <input type="submit" id="btnSubmit" value="Sumbit Order" />
            <input type="hidden" name="processMode" id="processMode" value="0" />
        </div>
    </div>
}
@section scripts{
    @*<script src="http://code.jquery.com/jquery-1.9.1.js"></script>*@
    <script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
    <script src="~/Scripts/jquery.multiselect.min.js"></script>
    <script type="text/javascript">
        var cityJson = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(activeCities))

        $(function () {
            $("#tabs").tabs();
            $("#symptomDropdown").multiselect();

            $("#frmCollectOrderInfo").show();

            if ($("#Address_State option:selected").val() != $("#Address_State option:eq(0)").val()) {
                UpdateCityOptions($("#Address_State"));
            }

            $("#btnTab0").click(function () {
                $("#tabs").tabs("option", "active", 1);
            });

            $("#btnTab1").click(function () {
                SummarizeOrder(true);
            });

            $("#btnSummarizeOrder").mouseover(function () {
                SummarizeOrder(false);
            });

            $("#copyBillingAddr").click(function () {
                if ($(this).is(':checked')) {
                    $("#Address_ShippingAddress").val($("#Address_BillingAddress").val());
                }
            });

            $("#Address_BillingAddress").change(function () {
                if ($("#copyBillingAddr").is(':checked')) {
                    $("#Address_ShippingAddress").val($(this).val());
                }
            });

            $(".symtomId").click(function () {
                var symptom = $('#des_' + $(this).attr('id'));
                if ($(this).is(':checked')) {
                    symptom.removeAttr('disabled');
                    symptom.removeClass("shadow");
                }
                else {
                    $('#des_' + $(this).attr('id')).attr('disabled', 'disabled');
                    symptom.addClass("shadow");
                }
            });

            $("#Address_State").change(function () {
                UpdateCityOptions($(this));
            });
        });

        function UpdateCityOptions(contextObj) {
            var newVal = $(contextObj).val();
            var html = "";
            var selectedCity = "";

            if (!newVal == false) {

               @if (Model.Address != null && !string.IsNullOrEmpty(Model.Address.City))
               {
                   @:html = '<option value="">- Select city -</option>';
                                   @:selectedCity = @Model.Address.City
               }
               else
               {
                   @:html = '<option value="" selected="selected">- Select city -</option>';
               }

                for (var i = 0; i < cityJson.length; i++) {
                    var cityItem = cityJson[i];

                    if (cityItem.StateID == newVal) {
                        if (selectedCity == cityItem.ID) {
                            html += '<option value="' + cityItem.ID + '" selected="selected">' + cityItem.CityName + '</option>';
                        }
                        else {
                            html += '<option value="' + cityItem.ID + '">' + cityItem.CityName + '</option>';
                        }
                        //html += '<option value="' + cityItem.ID + '">' + cityItem.CityName + '</option>';
                    }
                }
            }
            else {
                html = '<option value="" selected="selected">Wait for selected state</option>';
            }

            $(contextObj).closest("table").find("#Address_City option").remove();
            $(contextObj).closest("table").find("#Address_City").append(html);
        }


        var jsonDevice = @Html.Raw(Convert.ToString(ViewBag.JsonDeviceInf))

        function SummarizeOrder(changeTab) {
            if ($("#tabs-3").hasClass("calculated") == false) {

                var selectedSymptoms = $(".symtomId:checked");
                var symptomData = "";
                var symptomDes = "";

                for (var i = 0; i < selectedSymptoms.length; i++) {
                    var selectedNode = selectedSymptoms[i];
                    symptomData += "selectedSymptomIds=" + $(selectedNode).val() + "&";

                    var symptomName = $(selectedNode).parent("td").siblings("td:eq(0)").children("label").html();
                    var symptomText = $(selectedNode).parent("td").siblings("td:eq(1)").children("textarea").val();

                    symptomDes += "<tr><td><span>" + symptomName + "</span></td><td><span>" + symptomText + "</span></td></tr>"
                }

                $("#pricingSummary tr").not("#pricingSummary tr:eq(0)").detach();
                $("#symptomDes tr").not("#symptomDes tr:eq(0)").detach();

                $.ajax({
                    url: "/Home/CalculateOrderExpense",
                    data: symptomData,
                    type: 'POST',
                    dataType: "json",
                    async: false,
                    success: function (resp) {

                        var authenticated = resp.pop();

                        var pricingSummaryObj = $("#pricingSummary");
                        var html = "";
                        var total = 0;

                        for (var i = 0; i < resp.length; i++) {
                            var dataObj = resp[i];

                            var serviceDes = "<tr class='pricingDes'><td>Service Description</td><td><span>" + dataObj.Des + "</span></td></tr>"
                            var laborCost = "<tr><td>Labor Cost</td><td><span>$" + dataObj.LaborCost + "</span></td></tr>";
                            var discountLabor = "<tr><td>Discount on Labor Cost</td><td><span>$" + dataObj.DiscountLabor + "</span></td></tr>";
                            var partCost = "<tr><td>Part Cost</td><td><span>$" + dataObj.PartCost + "</span></td></tr>";
                            var discountPart = "<tr><td>Discount on Part Cost</td><td><span>$" + dataObj.DiscountPart + "</span></td></tr>";
                            var subTotal = "<tr class='subTotal'><td>Subtotal</td><td><span>$" + dataObj.Total + "</span></td></tr>";

                            total += parseFloat(dataObj.Total);
                            html += serviceDes + laborCost + discountLabor + partCost + discountPart + subTotal;
                        }

                        html += "<tr class='pricingDes subTotal'><td>Total</td><td><span>$" + total.toFixed(2) + "</span></td></tr>"

                        $(pricingSummaryObj).append(html);

                        if (authenticated.IsAuthenticated == false) {
                            $("#btnSubmit").hide();
                            //$("<p>Please <a href='/User/Login'>login</a> or <a href='/User/Register'>register</a> to continue</p>").insertAfter("#btnSubmit");
                            $("<p>Please <input type='submit' value='login' id='btnLoginSaveOrder' /> or <input type='submit' value='register' id='btnRegisterSaveOrder' /> to continue</p>").insertAfter("#btnSubmit");
                        }
                        else {
                            $("#btnSubmit").show();
                        }

                        $("#tabs-3").addClass("calculated");

                        $("#btnLoginSaveOrder").mouseover(function () {
                            $("#processMode").val("1");
                        });

                        $("#btnRegisterSaveOrder").mouseover(function () {
                            $("#processMode").val("2");
                        });
                    }
                });

                //$('#deviceType').html(jsonDevice.Type);

                $('#deviceBrand').html(jsonDevice.Brand);

                $('#deviceModel').html(jsonDevice.Model);

                //$('#deviceVersion').html(jsonDevice.Version);

                //$('#deviceManufacturer').html(jsonDevice.Manufacturer);

                var symtomNameArr = new Array();

                $("#symptomDropdown option:selected").each(function (index, el) {
                    symtomNameArr.push(el.innerText);
                });

                $('#symptomName').html(symtomNameArr.join(","));

                $('#symptomDes').append(symptomDes);

                $('#billingAddrSum').html($('#Address_BillingAddress').val());

                $('#shippingAddrSum').html($('#Address_ShippingAddress').val());

                $('#citysSum').html($("#Address_City option:selected").text());

                $('#stateSum').html($('#Address_State option:selected').text());

                $('#zipcodeSum').html($('#Address_ZipCode').val());

                if (changeTab === true) {
                    $("#tabs").tabs("option", "active", 2);
                }
            }
        }

    </script>
}
